import React, { PureComponent, Fragment } from 'react';
import { connect } from 'dva';
import moment from 'moment';
import {
  Row,
  Col,
  Card,
  Form,
  Input,
  Select,
  Icon,
  Button,
  Dropdown,
  Menu,
  InputNumber,
  DatePicker,
  Modal,
  message,
  Badge,
  Divider,
  Checkbox,
  Progress,
  Switch,
} from 'antd';
import StandardTable from 'components/StandardTable';
import PageHeaderLayout from '../../layouts/PageHeaderLayout';

import styles from './TaskList.less';

const { RangePicker } = DatePicker;
const FormItem = Form.Item;
const { Option } = Select;
const getValue = obj =>
  Object.keys(obj)
    .map(key => obj[key])
    .join(',');
// const statusMap = ['default', 'processing', 'success', 'error'];
const status = ['等待发布', '发布中', '发布成功', '发布异常'];
const statusMap = ['default', 'processing', 'success', 'error'];
const progressMap = ['normal', 'active', 'success', 'exception'];

@connect(({ task, loading }) => ({
  task,
  loading: loading.models.task,
}))
@Form.create()
export default class TaskList extends PureComponent {
  state = {
    modalVisible: false,
    expandForm: false,
    selectedRows: [],
    formValues: {},
    freshInterval: 30,
    isCheck: true,
  };

  componentDidMount() {
    const { progId } = this.props.match.params;
    const { dispatch } = this.props;
    dispatch({
      type: 'task/fetch',
      payload: { progId },
    });
    this.setState({ formValues: { progId } });

    // this.timer = setInterval(() => {
    //   dispatch({
    //     type: 'task/fetch',
    //     payload: { progId },
    //   });
    // }, 30000);
  }
  componentWillUnmount() {
    // clearInterval(this.timer);
  }
  // onChange = value => {
  //   this.setState({ freshInterval: value });
  //   this.onFresh(this.state.isCheck);
  // };

  onFresh = () => {
    // clearInterval(this.timer);
    // this.setState({ isCheck: checked });
    // const { progId } = this.props.match.params;
    // const value = this.state.freshInterval ? this.state.freshInterval * 1000 : 30000;
    // console.log('value', value);
    // if (checked) {
    //   this.timer = setInterval(() => {
    //     this.props.dispatch({
    //       type: 'task/fetch',
    //       payload: { progId },
    //     });
    //   }, value);
    // }
    const { progId } = this.props.match.params;
    this.props.dispatch({
      type: 'task/fetch',
      payload: { progId },
    });
  };
  handleStandardTableChange = (pagination, filtersArg, sorter) => {
    const { dispatch } = this.props;
    const { formValues } = this.state;

    const filters = Object.keys(filtersArg).reduce((obj, key) => {
      const newObj = { ...obj };
      newObj[key] = getValue(filtersArg[key]);
      return newObj;
    }, {});

    const params = {
      currentPage: pagination.current,
      pageSize: pagination.pageSize,
      ...formValues,
      ...filters,
    };
    if (sorter.field) {
      params.sorter = `${sorter.field}_${sorter.order}`;
    }

    dispatch({
      type: 'task/fetch',
      payload: params,
    });
  };

  handleFormReset = () => {
    const { form, dispatch } = this.props;
    form.resetFields();
    this.setState({
      formValues: {},
    });
    dispatch({
      type: 'task/fetch',
      payload: {},
    });
  };

  handleSearch = e => {
    e.preventDefault();

    const { dispatch, form } = this.props;

    form.validateFields((err, fieldsValue) => {
      if (err) return;
      const { progId, date } = fieldsValue;
      let values = {
        progId,
      };
      if (date) {
        const startTime = date[0].format('YYYY-MM-DD HH:mm:ss');
        const endTime = date[1].format('YYYY-MM-DD HH:mm:ss');
        values = {
          ...values,
          startTime,
          endTime,
        };
      }
      this.setState({
        formValues: values,
      });
      // console.log('values', values);
      dispatch({
        type: 'task/fetch',
        payload: values,
      });
    });
  };

  renderSimpleForm() {
    const { getFieldDecorator } = this.props.form;
    const { progId } = this.props.match.params;
    return (
      <Form onSubmit={this.handleSearch} layout="inline">
        <Row gutter={{ md: 8, lg: 24, xl: 48 }}>
          <Col md={6} sm={24}>
            <FormItem label="节目id">
              {getFieldDecorator('progId', {
                rules: [{ required: true, message: '请输入节目名称!' }],
                initialValue: progId === 'init' ? null : progId,
              })(<Input placeholder="请输入" />)}
            </FormItem>
          </Col>

          <Col md={6} sm={24}>
            <FormItem label="时间范围">
              {getFieldDecorator('date')(
                <RangePicker
                  showTime={{ format: 'HH:mm' }}
                  format="YYYY-MM-DD HH:mm"
                  placeholder={['Start Time', 'End Time']}
                  // onChange={onChange}
                  // onOk={onOk}
                  style={{ width: '100%' }}
                />
              )}
            </FormItem>
          </Col>
          <Col md={6} sm={24}>
            <span className={styles.submitButtons}>
              <Button type="primary" htmlType="submit" style={{ marginRight: 20 }}>
                查询
              </Button>

              {/* <a style={{ marginLeft: 8 }} onClick={this.toggleForm}>
                展开 <Icon type="down" />
              </a> */}
              <Button type="primary" onClick={this.onFresh}>
                刷新
              </Button>
            </span>
          </Col>
          <Col md={6} sm={24}>
            {/* <InputNumber
              min={10}
              max={600}
              defaultValue={30}
              onChange={this.onChange}
              style={{ marginRight: 10 }}
            />
            <Switch
              checkedChildren="刷新"
              unCheckedChildren="关闭"
              defaultChecked
              onChange={this.onFresh}
            /> */}
          </Col>
        </Row>
      </Form>
    );
  }

  renderForm() {
    return this.state.expandForm ? this.renderAdvancedForm() : this.renderSimpleForm();
  }

  render() {
    // //console.log('task', this.props.task);
    const { task, loading } = this.props;
    const { selectedRows } = this.state;
    const columns = [
      {
        title: '设备ID',
        dataIndex: 'devId',
        width: 200,
      },
      {
        title: '节目名称',
        dataIndex: 'progName',
        width: 200,
      },
      {
        title: '发布状态',
        dataIndex: 'pubStatus',
        width: 200,
        filters: [
          {
            text: status[0],
            value: 0,
          },
          {
            text: status[1],
            value: 1,
          },
          {
            text: status[2],
            value: 2,
          },
          {
            text: status[3],
            value: 3,
          },
        ],
        onFilter: (value, record) => record.pubStatus.toString() === value,
        render(val) {
          return <Badge status={statusMap[val]} text={status[val]} />;
        },
      },

      {
        title: '任务进度',
        dataIndex: 'progressRate',
        render(val, record) {
          const percent = val === null ? 0 : Number(val.split('%')[0]);
          //console.log('percent', percent);
          return (
            <Progress
              percent={percent}
              status={progressMap[record.pubStatus]}
              strokeWidth={6}
              style={{ width: 180 }}
            />
          );
        },
      },
      {
        title: '任务状态',
        dataIndex: 'statusInfo',
      },
      {
        title: '创建时间',
        dataIndex: 'createTime',
        sorter: true,
      },
      {
        title: '更新时间',
        dataIndex: 'updateTime',
        sorter: true,
      },
      // {
      //   title: 'Status',
      //   dataIndex: 'status',
      //   filters: [
      //     {
      //       text: status[0],
      //       value: 0,
      //     },
      //     {
      //       text: status[1],
      //       value: 1,
      //     },
      //     {
      //       text: status[2],
      //       value: 2,
      //     },
      //     {
      //       text: status[3],
      //       value: 3,
      //     },
      //   ],
      //   onFilter: (value, record) => record.status.toString() === value,
      //   render(val) {
      //     return <Badge status={statusMap[val]} text={status[val]} />;
      //   },
      // },
    ];

    return (
      <PageHeaderLayout title="任务查询">
        <Card bordered={false}>
          <div className={styles.tableList}>
            <div className={styles.tableListForm}>{this.renderForm()}</div>

            <StandardTable
              rowKey="pubId"
              selectedRows={selectedRows}
              loading={loading}
              data={task}
              columns={columns}
              onChange={this.handleStandardTableChange}
            />
          </div>
        </Card>
        {/* <CreateForm {...parentMethods} modalVisible={modalVisible} /> */}
      </PageHeaderLayout>
    );
  }
}
